#include <8052.h>
#include "I2C.h"
#include "misc.h"
//https://blog.csdn.net/weixin_41640116/article/details/104878646
//https://blog.csdn.net/qq_29350001/article/details/78623928

#include "MPU6050.h"

//MPU6050初始化
void MPU6050_Init()
{
    I2C_Init();

    //I2C_Start();
    // I2C_Send_Byte(MPU6050_Device_Address & 0); //读操作
    // I2C_Wait_ACK();
    //以下是连续写
    I2C_Send_To_Address(MPU6050_Device_Address, MPU6050_PWR_MGMT_1, 0x00);   //解除休眠状态
    I2C_Send_To_Address(MPU6050_Device_Address, MPU6050_SMPLRT_DIV, 0x07);   //陀螺仪采样率:1K/(1+0x07)=125Hz
    I2C_Send_To_Address(MPU6050_Device_Address, MPU6050_CONFIG, 0x06);       //低通滤波频率，典型值：0x06(5Hz),截止频率为1K,带宽为5Hz
    I2C_Send_To_Address(MPU6050_Device_Address, MPU6050_GYRO_CONFIG, 0x18);  //陀螺仪自检及测量范围，典型值：0x18(不自检，2000deg/s)
    I2C_Send_To_Address(MPU6050_Device_Address, MPU6050_ACCEL_CONFIG, 0x01); //配置加速度传感器工作在2G模式，不自检

    //I2C_Stop();
}

//EEPROM按地址读取
int MPU6050_ReadData(unsigned char reg_address)
{
    unsigned char H, L;
    H = I2C_Read_From_Address(MPU6050_Device_Address, reg_address);
    L = I2C_Read_From_Address(MPU6050_Device_Address, reg_address + 1);
    return ((H << 8) + L); //合成数据
}

//获取设备地址
unsigned char MPU6050_WHOAMI()
{
    return I2C_Read_From_Address(MPU6050_Device_Address, MPU6050_WHO_AM_I);
}

// int MPU6050_GYRO_DATA[3],MPU6050_ACCEL_DATA[3];
// 三轴加速度计的相关寄存器
// ACCEL_XOUT_H(0x3B)、ACCEL_XOUT_L(0x3C)、
// ACCEL_YOUT_H(0x3D)、ACCEL_YOUT_L(0x3E)、
// ACCEL_ZOUT_H(0x3F)、ACCEL_ZOUT_H(0x40)。

// 三轴陀螺仪的相关寄存器
// GYRO_XOUT_H(0x43)、GYRO_XOUT_L(0x44)、
// GYRO_YOUT_H(0x45)、GYRO_YOUT_L(0x46)、
// GYRO_ZOUT_H(0x47)、GYRO_ZOUT_L(0x48)。
int *MPU6050_GYRO()
{
    __xdata int MPU6050_GYRO_DATA[6] = {0, 0, 0};

    MPU6050_GYRO_DATA[0] = MPU6050_ReadData(0x43);
    // MPU6050_GYRO_DATA[1] = MPU6050_ReadData(0x44);
    MPU6050_GYRO_DATA[1] = MPU6050_ReadData(0x45);
    // MPU6050_GYRO_DATA[3] = MPU6050_ReadData(0x46);
    MPU6050_GYRO_DATA[2] = MPU6050_ReadData(0x47);
    // MPU6050_GYRO_DATA[5] = MPU6050_ReadData(0x48);
    return MPU6050_GYRO_DATA;
}